<template>
  <view class="coupon-history-page">
    <!-- 导航栏 -->
    <NavBar title="优惠券领取记录" />

    <!-- 筛选选项 -->
    <view class="filter-bar">
      <view class="filter-item" @click="showTimeFilter = true">
        <text>{{ timeFilterText }}</text>
        <DownArrow size="12" />
      </view>
      <view class="filter-item" @click="showStatusFilter = true">
        <text>{{ statusFilterText }}</text>
        <DownArrow size="12" />
      </view>
    </view>

    <!-- 优惠券记录列表 -->
    <view class="history-content">
      <!-- 空记录提示 -->
      <nut-empty v-if="historyList.length === 0" description="暂无优惠券领取记录" image="empty">
        <template #footer>
          <nut-button type="primary" size="small" @click="goCouponCenter">去领券</nut-button>
        </template>
      </nut-empty>

      <!-- 记录列表 -->
      <view v-else class="history-list">
        <view 
          v-for="(item, index) in historyList" 
          :key="index"
          class="history-item"
          :class="{
            'used': item.status === 'used',
            'expired': item.status === 'expired'
          }"
          @click="viewCouponDetail(item.coupon)"
        >
          <view class="history-left">
            <view class="coupon-amount">
              <text class="symbol">¥</text>
              <text class="value">{{ item.coupon.amount }}</text>
            </view>
            <view class="coupon-condition">满{{ item.coupon.minAmount }}元可用</view>
          </view>
          <view class="history-right">
            <view class="coupon-name">{{ item.coupon.name }}</view>
            <view class="coupon-scope">{{ item.coupon.scope }}</view>
            <view class="receive-time">领取时间：{{ formatDate(item.receiveTime) }}</view>
            <view class="coupon-status">
              <text :class="getStatusClass(item.coupon.status)">{{ getStatusText(item.coupon.status) }}</text>
            </view>
          </view>
          <view class="history-circle-top"></view>
          <view class="history-circle-bottom"></view>
        </view>
      </view>
    </view>

    <!-- 时间筛选弹窗 -->
    <nut-popup position="bottom" v-model:visible="showTimeFilter">
      <view class="filter-popup">
        <view class="popup-header">
          <view class="popup-title">时间筛选</view>
          <view class="popup-close" @click="showTimeFilter = false">
            <Close />
          </view>
        </view>
        <view class="popup-content">
          <view 
            v-for="(item, index) in timeFilterOptions" 
            :key="index"
            class="filter-option"
            :class="{ 'active': timeFilter === item.value }"
            @click="selectTimeFilter(item.value)"
          >
            {{ item.label }}
          </view>
        </view>
      </view>
    </nut-popup>

    <!-- 状态筛选弹窗 -->
    <nut-popup position="bottom" v-model:visible="showStatusFilter">
      <view class="filter-popup">
        <view class="popup-header">
          <view class="popup-title">状态筛选</view>
          <view class="popup-close" @click="showStatusFilter = false">
            <Close />
          </view>
        </view>
        <view class="popup-content">
          <view 
            v-for="(item, index) in statusFilterOptions" 
            :key="index"
            class="filter-option"
            :class="{ 'active': statusFilter === item.value }"
            @click="selectStatusFilter(item.value)"
          >
            {{ item.label }}
          </view>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar/index.vue'
import userApi from '@/api/user'
import type { Coupon } from '@/types/http'
import { useLoading } from '@/hooks/useLoading'
import { DownArrow, Close } from '@nutui/icons-vue-taro'

// 历史记录列表
interface HistoryItem {
  id: string | number;
  coupon: Coupon;
  receiveTime: string;
}

const historyList = ref<HistoryItem[]>([])

// 加载状态
const { loading, showLoading, hideLoading } = useLoading()

// 筛选条件
const timeFilter = ref('all')
const statusFilter = ref('all')

// 筛选弹窗显示状态
const showTimeFilter = ref(false)
const showStatusFilter = ref(false)

// 时间筛选选项
const timeFilterOptions = [
  { label: '全部时间', value: 'all' },
  { label: '最近一周', value: 'week' },
  { label: '最近一个月', value: 'month' },
  { label: '最近三个月', value: 'quarter' },
]

// 状态筛选选项
const statusFilterOptions = [
  { label: '全部状态', value: 'all' },
  { label: '未使用', value: 'unused' },
  { label: '已使用', value: 'used' },
  { label: '已过期', value: 'expired' },
]

// 筛选文本
const timeFilterText = computed(() => {
  const option = timeFilterOptions.find(item => item.value === timeFilter.value)
  return option ? option.label : '全部时间'
})

const statusFilterText = computed(() => {
  const option = statusFilterOptions.find(item => item.value === statusFilter.value)
  return option ? option.label : '全部状态'
})

// 选择时间筛选
const selectTimeFilter = (value: string) => {
  timeFilter.value = value
  showTimeFilter.value = false
  getHistoryList()
}

// 选择状态筛选
const selectStatusFilter = (value: string) => {
  statusFilter.value = value
  showStatusFilter.value = false
  getHistoryList()
}

// 获取优惠券领取记录
const getHistoryList = async () => {
  try {
    showLoading('加载中...')
    
    // 这里应该调用获取优惠券领取记录的API
    // 由于API中没有直接提供，使用模拟数据
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    const mockData: HistoryItem[] = [
      {
        id: '1',
        coupon: {
          id: '101',
          name: '新人专享券',
          amount: '15',
          minAmount: '100',
          scope: '全场通用',
          categoryId: '',
          validTimeDesc: '2023-06-01 ~ 2023-07-01',
          status: 'unused'
        },
        receiveTime: '2023-06-05 14:30:25'
      },
      {
        id: '2',
        coupon: {
          id: '102',
          name: '满减优惠券',
          amount: '30',
          minAmount: '200',
          scope: '全场通用',
          categoryId: '',
          validTimeDesc: '2023-05-01 ~ 2023-06-01',
          status: 'used'
        },
        receiveTime: '2023-05-15 09:45:12'
      },
      {
        id: '3',
        coupon: {
          id: '103',
          name: '数码专享券',
          amount: '50',
          minAmount: '300',
          scope: '数码专区',
          categoryId: '1',
          validTimeDesc: '2023-04-01 ~ 2023-05-01',
          status: 'expired'
        },
        receiveTime: '2023-04-10 16:20:33'
      },
      {
        id: '4',
        coupon: {
          id: '104',
          name: '服装专享券',
          amount: '20',
          minAmount: '150',
          scope: '服装专区',
          categoryId: '2',
          validTimeDesc: '2023-06-01 ~ 2023-07-01',
          status: 'unused'
        },
        receiveTime: '2023-06-02 11:15:40'
      },
      {
        id: '5',
        coupon: {
          id: '105',
          name: '家电专享券',
          amount: '100',
          minAmount: '1000',
          scope: '家电专区',
          categoryId: '3',
          validTimeDesc: '2023-06-01 ~ 2023-07-01',
          status: 'unused'
        },
        receiveTime: '2023-06-03 10:05:18'
      }
    ]
    
    // 根据筛选条件过滤数据
    historyList.value = mockData.filter(item => {
      // 状态筛选
      const statusMatch = statusFilter.value === 'all' || item.coupon.status === statusFilter.value
      
      // 时间筛选
      let timeMatch = true
      const receiveDate = new Date(item.receiveTime)
      const now = new Date()
      
      if (timeFilter.value === 'week') {
        const weekAgo = new Date()
        weekAgo.setDate(now.getDate() - 7)
        timeMatch = receiveDate >= weekAgo
      } else if (timeFilter.value === 'month') {
        const monthAgo = new Date()
        monthAgo.setMonth(now.getMonth() - 1)
        timeMatch = receiveDate >= monthAgo
      } else if (timeFilter.value === 'quarter') {
        const quarterAgo = new Date()
        quarterAgo.setMonth(now.getMonth() - 3)
        timeMatch = receiveDate >= quarterAgo
      }
      
      return statusMatch && timeMatch
    })
    
  } catch (error) {
    console.error('获取优惠券领取记录失败', error)
    Taro.showToast({
      title: '获取记录失败',
      icon: 'none'
    })
  } finally {
    hideLoading()
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'unused':
      return '未使用'
    case 'used':
      return '已使用'
    case 'expired':
      return '已过期'
    default:
      return '未知状态'
  }
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  switch (status) {
    case 'unused':
      return 'status-unused'
    case 'used':
      return 'status-used'
    case 'expired':
      return 'status-expired'
    default:
      return ''
  }
}

// 查看优惠券详情
const viewCouponDetail = (coupon: Coupon) => {
  Taro.navigateTo({
    url: `/pages/coupon/detail?id=${coupon.id}`
  })
}

// 去领券中心
const goCouponCenter = () => {
  Taro.navigateTo({
    url: '/pages/coupon/center'
  })
}

// 组件挂载时初始化
onMounted(() => {
  getHistoryList()
})
</script>

<style lang="scss" scoped>
.coupon-history-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
  
  .filter-bar {
    display: flex;
    padding: 12px 15px;
    background-color: #fff;
    margin-bottom: 10px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    
    .filter-item {
      display: flex;
      align-items: center;
      margin-right: 20px;
      font-size: 14px;
      color: #666;
      
      .nut-icon {
        margin-left: 4px;
      }
    }
  }
  
  .history-content {
    padding: 10px;
    
    .history-list {
      .history-item {
        position: relative;
        display: flex;
        margin-bottom: 15px;
        height: 100px;
        background: linear-gradient(to right, #fa2c19, #fa6419);
        border-radius: 8px;
        color: #fff;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(250, 44, 25, 0.2);
        
        &.used {
          background: linear-gradient(to right, #8e8e8e, #a0a0a0);
          box-shadow: 0 2px 8px rgba(142, 142, 142, 0.2);
        }
        
        &.expired {
          background: linear-gradient(to right, #a0a0a0, #c0c0c0);
          box-shadow: 0 2px 8px rgba(160, 160, 160, 0.2);
        }
        
        .history-left {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 120px;
          border-right: 1px dashed rgba(255, 255, 255, 0.3);
          
          .coupon-amount {
            display: flex;
            align-items: baseline;
            
            .symbol {
              font-size: 16px;
              margin-right: 2px;
            }
            
            .value {
              font-size: 30px;
              font-weight: bold;
            }
          }
          
          .coupon-condition {
            font-size: 12px;
            margin-top: 5px;
          }
        }
        
        .history-right {
          flex: 1;
          padding: 15px;
          position: relative;
          
          .coupon-name {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
          }
          
          .coupon-scope {
            font-size: 12px;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
          }
          
          .receive-time {
            font-size: 12px;
            opacity: 0.8;
            margin-bottom: 5px;
          }
          
          .coupon-status {
            font-size: 12px;
            
            .status-unused {
              color: #fff;
              background-color: rgba(255, 255, 255, 0.2);
              padding: 2px 6px;
              border-radius: 10px;
            }
            
            .status-used {
              color: #fff;
              background-color: rgba(255, 255, 255, 0.2);
              padding: 2px 6px;
              border-radius: 10px;
            }
            
            .status-expired {
              color: #fff;
              background-color: rgba(255, 255, 255, 0.2);
              padding: 2px 6px;
              border-radius: 10px;
            }
          }
        }
        
        .history-circle-top,
        .history-circle-bottom {
          position: absolute;
          left: 110px;
          width: 20px;
          height: 20px;
          background-color: #f5f5f5;
          border-radius: 50%;
        }
        
        .history-circle-top {
          top: -10px;
        }
        
        .history-circle-bottom {
          bottom: -10px;
        }
      }
    }
  }
  
  .filter-popup {
    padding: 15px;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .popup-title {
        font-size: 16px;
        font-weight: 500;
      }
      
      .popup-close {
        padding: 5px;
      }
    }
    
    .popup-content {
      .filter-option {
        padding: 12px 0;
        font-size: 14px;
        border-bottom: 1px solid #f5f5f5;
        
        &.active {
          color: #fa2c19;
        }
        
        &:last-child {
          border-bottom: none;
        }
      }
    }
  }
  
  :deep(.nut-empty) {
    padding: 40px 0;
  }
}
</style>